import {
  HOME_PAGE,
  TAB_PAGE,
  ROUTER_ACCESS,
  ROUTER_ALIAS,
  PAGE_CONFIG,
  PAGE_USING,
  hasOwn,
} from '@shared';

import { createPageAlias } from '@core/util';

const INCLUDE_KEY = 'include';
const EXCLUDE_KEY = 'exclude';

function findAccessValue(accessKey, optionKey, list) {
  return list[accessKey][optionKey];
}

export function parseRouters(routers) {
  const routerAlias = {};
  const routerAccess = {};
  let homePage = '';
  let tabList = [];
  for (var i = 0, size = routers.length; i < size; i++) {
    const router = routers[i];
    const pageConfig = router[PAGE_CONFIG];

    if (
      pageConfig &&
      hasOwn(pageConfig, PAGE_USING) &&
      !pageConfig[PAGE_USING]
    ) {
      continue;
    }
    const pagePath = router.path;
    const pageAlias = router[ROUTER_ALIAS]
      ? router[ROUTER_ALIAS]
      : createPageAlias(pagePath);
    routerAlias[pageAlias] = pagePath;
    if (hasOwn(router, HOME_PAGE)) {
      homePage = router.path;
    }
    if (hasOwn(router, TAB_PAGE)) {
      tabList.push(router.path);
    }
    if (hasOwn(router, PAGE_CONFIG)) {
      const options = pageConfig.access;
      if (options) {
        if (hasOwn(options, INCLUDE_KEY)) {
          let includeValues = options[INCLUDE_KEY];
          if (typeof includeValues === 'string') {
            includeValues = [includeValues];
          }
          // 查找一下有没有记录这个权限
          includeValues.forEach((value) => {
            if (!hasOwn(routerAccess, value)) {
              routerAccess[value] = {
                [INCLUDE_KEY]: [],
                [EXCLUDE_KEY]: [],
              };
            }
            routerAccess[value][INCLUDE_KEY].push(pagePath);
          });
        }
        if (hasOwn(options, EXCLUDE_KEY)) {
          let excludeValues = options[EXCLUDE_KEY];
          if (typeof excludeValues === 'string') {
            excludeValues = [excludeValues];
          }
          // 查找一下有没有记录这个权限
          excludeValues.forEach((value) => {
            if (!hasOwn(routerAccess, value)) {
              routerAccess[value] = {
                [INCLUDE_KEY]: [],
                [EXCLUDE_KEY]: [],
              };
            }
            routerAccess[value][EXCLUDE_KEY].push(pagePath);
          });
        }
        delete router[ROUTER_ACCESS];
      }
    }
  }
  return {
    routerAccess,
    routerAlias: {
      HOME_PAGE: homePage,
      TAB_LIST: tabList,
      ...routerAlias,
    },
  };
}
